package com.dshore.messagecenter.dao.warning;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.dshore.messagecenter.model.basedata.MdApp;
import com.dshore.messagecenter.model.topicqueue.MdTopic;
import com.dshore.messagecenter.model.warning.MrExceptionMessage;
import com.dshore.messagecenter.util.UUIDUtil;

@Repository
public class ExceptionMessageDao {
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	/**
	 * 数据总记录数
	 * @param exceptionMessage
	 * @return
	 */
	public long queryCountByPrama(MrExceptionMessage exceptionMessage) {
		String topicQueueNo = exceptionMessage.getTopicQueueNo();
		String appCode = exceptionMessage.getAppCode();
		List<Object> list=new ArrayList<>();
		StringBuffer sql=new StringBuffer();
		sql.append("select count(1) from");
		 sql.append(" (select count(1) from T_MR_EXCEPTION_MESSAGE where Del_FLAG=0 ");
		 if(StringUtils.isNotBlank(topicQueueNo)) {
			 sql.append("and TOPIC_QUEUE_NO = ? ");
			 list.add(topicQueueNo);
		 }
		 if(StringUtils.isNotBlank(appCode)) {
			 sql.append("and APP_CODE = ? ");
			 list.add(appCode);
		 }
		 sql.append("group by APP_CODE,TOPIC_QUEUE_NO ) n");
		 Object[]args=list.toArray();
		return jdbcTemplate.queryForObject(sql.toString(),args,long.class);
	}
	/**
	 * 查询所有数据
	 * @param exceptionMessage
	 * @return
	 */
	public List<MrExceptionMessage> queryListByPrama(MrExceptionMessage exceptionMessage) {
		String topicQueueNo = exceptionMessage.getTopicQueueNo();
		String appCode = exceptionMessage.getAppCode();
		List<Object> list=new ArrayList<>();
		StringBuffer sql = new StringBuffer();
		sql.append("select * from (");
		sql.append("select A.*, rownum rn from (SELECT APP_CODE,TOPIC_QUEUE_NO,URL FROM T_MR_EXCEPTION_MESSAGE  where del_flag = 0 ");		
		if(StringUtils.isNotBlank(topicQueueNo)) {
			sql.append("and TOPIC_QUEUE_NO = ?");
			 list.add(topicQueueNo);
		}
		 if(StringUtils.isNotBlank(appCode)) {
			 sql.append("and APP_CODE = ?");
			 list.add(appCode);
		 }
		sql.append(" group by APP_CODE,TOPIC_QUEUE_NO,URL");
		sql.append(" ) A   )");
		sql.append(" where rn between ? and ? ");
		//sql.append(" order by CREATED_TIME desc ");
		list.add(exceptionMessage.getOffset()+1);
		list.add(exceptionMessage.getOffset()+exceptionMessage.getLimit());
		Object[]args=list.toArray();
		RowMapper<MrExceptionMessage> rowMapper = new BeanPropertyRowMapper<>(MrExceptionMessage.class);
		return jdbcTemplate.query(sql.toString(),args, rowMapper);
	}
	
	/**
	 * 获取表格字段
	 * @param exceptionMessage1
	 * @return
	 */
	public Map<String, Object> selectFieldName(MrExceptionMessage exceptionMessage1) {
		List<Object> list=new ArrayList<>();
		StringBuffer sql = new StringBuffer();
		sql.append("select * from (select nvl((select TOPIC_QUEUE_NAME  from T_MD_TOPIC where TOPIC_QUEUE_NO=? and DEL_FLAG=0),null) as Topic_Queue_Name  from dual)");
		list.add(exceptionMessage1.getTopicQueueNo());
		sql.append(",(select nvl((select STATUS  from T_MD_TOPIC where TOPIC_QUEUE_NO=? and DEL_FLAG=0),null) as status  from dual)");
		list.add(exceptionMessage1.getTopicQueueNo());
		sql.append(",(select nvl((select APP_NAME  from T_MD_APP where APP_CODE=? and DEL_FLAG=0),null) as App_Name from dual)");
		list.add(exceptionMessage1.getAppCode());
		sql.append(",(select count(1) as \"number\",max(CREATED_TIME) as latestTime from T_MR_EXCEPTION_MESSAGE where TOPIC_QUEUE_NO=? and DEL_FLAG=0");
		list.add(exceptionMessage1.getTopicQueueNo());
		sql.append(" and APP_CODE=?)");
		list.add(exceptionMessage1.getAppCode());
		sql.append(",(select nvl((select TARGET_URL  from T_MD_TOPIC_SEND where TOPIC_QUEUE_NO=? ");
		list.add(exceptionMessage1.getTopicQueueNo());
		sql.append("and TARGET_APPID = (select ID from T_MD_APP where APP_CODE =?) AND DEL_FLAG=0),null) as \"url\" from dual)");
		list.add(exceptionMessage1.getAppCode());
		Object[] args=list.toArray();
		try {
				return jdbcTemplate.queryForMap(sql.toString(),args);
		}catch(DataAccessException e) {
			return null;
		}
	}
	
	/**
	 * 获取主题队列名称下拉
	 * @return
	 */
	public List<MdTopic> getTopicName() {
		String sql = "select TOPIC_QUEUE_NO,TOPIC_QUEUE_NAME from T_MD_TOPIC where DEL_FLAG=0";
		RowMapper<MdTopic> rowMapper = new BeanPropertyRowMapper<>(MdTopic.class);
		return jdbcTemplate.query(sql,rowMapper);
	}
	
	/**
	 * 获取应用名称下拉
	 * @return
	 */
	public List<MdApp> getAppName(){
		String sql="select APP_CODE,APP_NAME from T_MD_APP where DEL_FLAG=0";
		RowMapper<MdApp> rowMapper = new BeanPropertyRowMapper<>(MdApp.class);
		return jdbcTemplate.query(sql,rowMapper);
		
	}
	
	/**
	 * 删除
	 * @param id
	 * @return
	 */
	public void deleteByCodes(String[] app,String[] topic) {
		String sql="update T_MR_EXCEPTION_MESSAGE set del_flag=1,modified_time=?  where APP_CODE =? and TOPIC_QUEUE_NO=?";	
		 jdbcTemplate.batchUpdate(sql,new BatchPreparedStatementSetter() {
			
			@Override
			public void setValues(PreparedStatement ps, int i) throws SQLException {
				ps.setTimestamp(1, new Timestamp(System.currentTimeMillis()));
				ps.setString(2, app[i].toString());
				ps.setString(3, topic[i].toString());
			}			
			@Override
			public int getBatchSize() {
				return app.length;
			}
		});
	}
	
	
	/**
	 * 异常信息添加
	 * @param list
	 */
	public int[] addException(List<MrExceptionMessage> exceptionMessages) {
		String sql="insert into T_MR_EXCEPTION_MESSAGE(ID,TOPIC_QUEUE_NO,MESSAGE_CONTENT,APP_CODE,CREATED_TIME,DEL_FLAG) values(?,?,?,?,?,?)";
		List<Object[]> records = new ArrayList<Object[]>();
		Date now = new Date();
		for(MrExceptionMessage exceptionMessage:exceptionMessages) {
			records.add(new Object[]{UUIDUtil.getUUId(),exceptionMessage.getTopicQueueNo(),exceptionMessage.getMessageContentString().getBytes(),
					exceptionMessage.getAppCode(),now,0});
		}
		return jdbcTemplate.batchUpdate(sql, records);
		
	}
	
	
	/**
	 * 重发查询信息
	 * @param topicQueueNo
	 * @param appCode
	 * @return
	 */
	public  List<MrExceptionMessage> queryData(String topicQueueNo,String appCode){
		String sql="select * from T_MR_EXCEPTION_MESSAGE where TOPIC_QUEUE_NO=? and APP_CODE=? and DEL_FLAG=?";
		RowMapper<MrExceptionMessage> rowMapper = new BeanPropertyRowMapper<>(MrExceptionMessage.class);
		return jdbcTemplate.query(sql,rowMapper,topicQueueNo,appCode,0);		
	}
	/**
	 * 重发删除
	 */
	public Integer deleteAfterResend(String topicQueueNo,String appCode) {
		String sql = "update T_MR_EXCEPTION_MESSAGE set DEL_FLAG=? where APP_CODE =? and TOPIC_QUEUE_NO=? and DEL_FLAG=?";
		try{
			jdbcTemplate.update(sql, 1,appCode,topicQueueNo,0);
			return 200;
		}catch(Exception e) {
			return 400;
		}
	}
	
	/**
	 * 删除主题队列异常信息也删除
	 */
	public Integer deleteByTopicDeleted(String[] topicQueueNo) {
		String sql="update T_MR_EXCEPTION_MESSAGE set del_flag=1,modified_time=?  where TOPIC_QUEUE_NO=?";	
		jdbcTemplate.batchUpdate(sql,new BatchPreparedStatementSetter() {
			
			@Override
			public void setValues(PreparedStatement ps, int i) throws SQLException {
				ps.setTimestamp(1, new Timestamp(System.currentTimeMillis()));
				ps.setString(2, topicQueueNo[i].toString());
			}			
			@Override
			public int getBatchSize() {
				return topicQueueNo.length;
			}
		});
	return 1;
	}
}
